using System;
using System.Collections.Generic;
using System.Linq;
using ApiProject.Api.Data;
using ApiProject.Api.Entity;
using ApiProject.Api.PramaModel;
using ApiProject.Api.Repository;
using ApiProject.Api.Uitls;
using ApiProject.Api.Utils;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;


// 后台用户管理
namespace ApiProject.Api.Controllers
{
    // [Authorize]
    [ApiController]
    [Route("[controller]")]
    public class UserManageController : ControllerBase
    {
        private IRepository<Users> _usersRepository;

        private IRepository<UserInfo> _userInfoRepository;

        private IRepository<Roles> _roleRepository;


        private Token _tokenParameter;

        private readonly IConfiguration _configuration;

        private readonly IWebHostEnvironment _hostingEnvironment;

        public UserManageController(
            IConfiguration configuration,
            IRepository<Users> usersRepository,
            IRepository<UserInfo> userInfoRepository,
            IWebHostEnvironment hostingEnvironment,
            IRepository<Roles> roleRepository
        )
        {
            _usersRepository = usersRepository;
            _configuration = configuration;
            _userInfoRepository = userInfoRepository;
            _tokenParameter =
                _configuration.GetSection("TokenParameter").Get<Token>();
            _hostingEnvironment = hostingEnvironment;
            _roleRepository = roleRepository;
        }

        // 后台管理系统 用户管理 分页显示用户列表
        // Get：/usermanage
        [HttpGet("{id}")]
        public dynamic Get(int id, [FromQuery] Pages page)
        {
            if (id == 0)
            {
                var pageIndex = page.pageIndex;
                var pageSize = page.pageSize;
                var users = _usersRepository.Table.Include(p => p.UserInfo).Where(o => o.IsDelete == false && o.Id != 1).ToList();
                var userRole = from userAll in users
                               join r in _roleRepository.Table on userAll.RolesId equals r.Id
                               select new { userAll.Username, userAll.Password, userAll.IsEnable, userAll.Id, userAll.UserInfo, userAll.Remarks, r.RoleName };
                var u = userRole.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();

                return JsonHelper.Serialize(new
                {
                    Code = 200,
                    Data = new { Data = u, pager = new { pageIndex, pageSize, rowsTotal = users.Count() } },
                    Msg = "获取成功"
                });
            }
            else
            {
                var pageIndex = page.pageIndex;
                var pageSize = page.pageSize;
                var users = _usersRepository.Table.Include(p => p.UserInfo).Where(o => o.IsDelete == false && o.RolesId == id && o.Id != 1).ToList();
                var userRole = from userAll in users
                               join r in _roleRepository.Table on userAll.RolesId equals r.Id
                               select new { userAll.Username, userAll.Password, userAll.IsEnable, userAll.Id, userAll.UserInfo, userAll.Remarks, r.RoleName };
                var u = userRole.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();

                return JsonHelper.Serialize(new
                {
                    Code = 200,
                    Data = new { Data = u, pager = new { pageIndex, pageSize, rowsTotal = users.Count() } },
                    Msg = "获取成功"
                });
            }

        }

        //管理员修改用户信息
        // Put： /usermanage/{id}
        //参数：user的id user数据
        // [AllowAnonymous]
        [HttpPut("{id}")]
        public dynamic Put(int id, NewUser model)
        {
            var user = _usersRepository.GetById(id);
            var userInfo = _userInfoRepository.Table.Where(x => x.UserId == id).FirstOrDefault();
            if (user != null)
            {
                //修改user表的数据
                user.Username = model.Username.Trim();
                user.Password = model.Password.Trim();
                user.Remarks = model.Remarks;
                user.UpdateTime = DateTime.Now;

                _usersRepository.Update(user);

                userInfo.NickName = model.NickName.Trim();
                userInfo.UpdateTime = DateTime.Now;
                _userInfoRepository.Update(userInfo);
                return JsonHelper.Serialize(new
                {
                    Code = 200,
                    Data = user,
                    Msg = string.Format("成功修改Id为{0}的用户", id)
                });
            }
            else
            {
                return JsonHelper.Serialize(new { Code = 1000, Data = "", Msg = "修改失败" });
            }
        }

        //伪删除用户
        // post /usermanage/delete 
        // 参数： user的id
        [HttpPost, Route("delete/{id}")]
        public dynamic IsDelete(int id)
        {
            var user = _usersRepository.GetById(id);

            if (user != null)
            {
                user.IsDelete = true;
                user.UpdateTime = DateTime.Now;

                _usersRepository.Update(user);
                return JsonHelper.Serialize(new
                {
                    Code = 200,
                    Data = user,
                    Msg = string.Format("成功在表中删除Id为{0}的用户", id)
                });
            }
            else
            {
                return JsonHelper.Serialize(new { Code = 1000, Data = "", Msg = "删除失败" });
            }
        }


        //禁用用户
        // Post /usermanage/isenable/{id}
        // 参数 user的id
        [HttpPost, Route("isenable/{id}")]
        public dynamic IsEnable(int id, NewUser model)
        {
            var user = _usersRepository.GetById(id);

            var num = model.isEnable;

            if (user != null)
            {
                if (num == false)
                {
                    user.IsEnable = false;
                    user.UpdateTime = DateTime.Now;
                    _usersRepository.Update(user);
                    return JsonHelper.Serialize(new
                    {
                        Code = 200,
                        Data = user,
                        Msg = string.Format("已禁用Id为{0}的用户", id)
                    });
                }
                else
                {
                    user.IsEnable = true;
                    user.UpdateTime = DateTime.Now;
                    _usersRepository.Update(user);
                    return JsonHelper.Serialize(new
                    {
                        Code = 200,
                        Data = user,
                        Msg = string.Format("已启用Id为{0}的用户", id)
                    });
                }

            }
            else
            {
                return JsonHelper.Serialize(new { Code = 1000, Data = "", Msg = "禁用失败" });
            }
        }

        //添加用户
        // Post /usermanage
        [HttpPost]
        public dynamic Post(NewUser model)
        {
            var username = model.Username.Trim();
            var password = model.Password.Trim();
            var nickname = model.NickName.Trim();
            var remarks = model.Remarks;
            var roleId = model.RolesId;

            // 判断传入的username是否为空
            if (string.IsNullOrEmpty(username))
            {
                var temp =
                    new
                    {
                        Code = 1000,
                        Data = "",
                        Msg = "用户名不能为空，请输入用户名"
                    };
                return JsonHelper.Serialize(temp);
            }
            else
            {
                var users = _usersRepository.Table.Where(x => x.Username == username).FirstOrDefault();
                //判断是否存在该用户
                if (users != null)
                {

                    if (users.IsDelete == true)
                    {
                        var user = new Users
                        {
                            Username = username,
                            Password = password,
                            Remarks = remarks,
                            RolesId = roleId
                        };
                        _usersRepository.Insert(user);
                        _usersRepository.Table.Where(x => x.Username == username).FirstOrDefault();
                        var userInfro = new UserInfo
                        {
                            UserId = user.Id,
                            NickName = nickname
                        };

                        _userInfoRepository.Insert(userInfro);

                        var usersAll = _usersRepository.Table.Include(p => p.UserInfo).Where(o => o.Id == user.Id).ToList();
                        var userRole = from userAll in usersAll
                                       join r in _roleRepository.Table on userAll.RolesId equals r.Id
                                       select new { userAll.Username, userAll.Password, userAll.IsEnable, userAll.Id, userAll.UserInfo, userAll.Remarks, r.RoleName };

                        return JsonHelper
                            .Serialize(new
                            {
                                Code = 200,
                                Data = userRole,
                                Msg = "创建用户成功"
                            });
                    }
                    else
                    {
                        return JsonHelper.Serialize(new
                        {
                            Code = 1000,
                            Data = "",
                            Msg = "用户名已存在，请重新输入用户名"
                        });
                    }
                }
                else
                {
                    var user =
                        new Users
                        {
                            Username = username,
                            Password = password,
                            Remarks = remarks,
                            RolesId = roleId
                        };
                    _usersRepository.Insert(user);
                    _usersRepository.Table.Where(x => x.Username == username).FirstOrDefault();
                    var userInfro = new UserInfo
                    {
                        UserId = user.Id,
                        NickName = nickname
                    };

                    _userInfoRepository.Insert(userInfro);


                    var usersAll = _usersRepository.Table.Include(p => p.UserInfo).Where(o => o.Id == user.Id).ToList();
                    var userRole = from userAll in usersAll
                                   join r in _roleRepository.Table on userAll.RolesId equals r.Id
                                   select new { userAll.Username, userAll.Password, userAll.IsEnable, userAll.Id, userAll.UserInfo, userAll.Remarks, r.RoleName };

                    return JsonHelper
                        .Serialize(new
                        {
                            Code = 200,
                            Data = userRole,
                            Msg = "创建用户成功"
                        });
                }
            }
        }



        // 获取已启用的用户角色
        //Get /usermanage/roles
        [HttpGet,Route("roles")]
        public dynamic GetRoles(){
            var roles = _roleRepository.Table.Where(x => x.IsDelete == false && x.IsEnable == true).ToList();

            return JsonHelper.Serialize(new {
                Code = 200,
                Data = roles,
                Msg = "查找角色成功"
            });
        }




    }
}
